<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use Think\Log;
use Think\Controller;
use Think\Controller\RestController;
use Com\Wechat\JsApiPay;
use Com\Wechat\MicroPay;
use Com\Wechat\lib\WxPayUnifiedOrder;
use Com\Wechat\lib\WxPayMicroPay;
use Com\Wechat\lib\WxPayApi;
use Com\Wechat\WechatApi;
use Com\Wechat\Wechat;
use Com\Wechat\TemplateMessage;
use Com\Wechat\lib\WxPayNotify;
use Think\Exception;
use Com\Wechat\AccessToken;
use Com\Wechat\Card\Signature;
/**
 * 模型数据管理控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class BuyticketsController extends ThinkController{

  public function ticketslists(){
    $data = M('ticket')
    ->field('ticket.*,exhibition.name as ex_name')
    ->where(array('status'=>1))
    ->join('exhibition on exhibition.id = ticket.exhibition_id','left')
    ->select();
    foreach ($data as $key => $value) {
      # code...
      $data[$key]['begin_date'] = date('Y-m-d',$value['begin_date']);
      $data[$key]['end_date'] = date('Y-m-d',$value['end_date']);
    }
    $this->assign('list_data', $data);
    $this->display('Buytickets/buytickets');
  }

  public function ticketsliststest(){
    $data = M('ticket')
    ->field('ticket.*,exhibition.name as ex_name')
    ->where(array('status'=>1))
    ->join('exhibition on exhibition.id = ticket.exhibition_id','left')
    ->select();
    foreach ($data as $key => $value) {
      # code...
      $data[$key]['begin_date'] = date('Y-m-d',$value['begin_date']);
      $data[$key]['end_date'] = date('Y-m-d',$value['end_date']);
    }
    $this->assign('list_data', $data);
    $this->display('Buytickets/buyticketstest');
  }

  public function ticketinfo(){
    $ticketId = I('get.ticketId');
    $data = M('ticket')
    ->field('ticket.*,exhibition.name as ex_name')
    ->where(array('status'=>1,'ticket.id'=>$ticketId))
    ->join('exhibition on exhibition.id = ticket.exhibition_id','left')
    ->find();
    $this->success($data);
  }

  public function buy(){
    $post = $_POST;
    $ticket_id = $post['ticket_id'];
    if(!$ticket_id){
      $this->error('缺少票务号');
    }
    $amount = $post['amount'];
    if(!$amount||$amount<=0){
      $this->error('请至少购买一张票！');
    }
    if(!$post['payment']){
      $this->error('请选择支付方式！');
    }

    // 生成购票订单
    // 查询ticket信息
    $re_ticket = M('ticket')->find($ticket_id);
    //票券错误信息处理
    $current_date = time();
    if($current_date<$re_ticket['begin_date']){
      $this->error('很抱歉，您选择的票券还未开售！');
    }
    if($current_date>($re_ticket['end_date']+3600*24)){
      $this->error('很抱歉，您选择的票券已停售！');
    }
    if($re_ticket['stock']<=0){
      $this->error('很抱歉，您选择的票券已售罄！');
    }

    $post['create_time'] = time();
    $post['site'] = 2;
    $post['price'] = $re_ticket['price'];
    $post['activity_price'] = $re_ticket['price_activity'];
    
    // 支付状态为已支付
    $post['status'] = 1;
    // 生成ticket_order订单
    $re_order = M('ticket_order')->add($post);
    $date = date("Ymd");
    // 更新订单号
    M('ticket_order')->where(array('id'=>$re_order))->save(array('order_num'=>$date.$re_order));

    for($i=0;$i<$amount;$i++){
      $data['ticket_order_id'] = $re_order;
      $data['create_time'] = time();
      $data['redeem_time'] = $data['create_time'];
      $data['status'] = 1;

      $re_redeem = M('ticket_redeem_code')->add($data);
      $len = strlen($re_redeem);
      $id = substr($re_redeem,($len-2));
      M('ticket_redeem_code')->where(array('id'=>$re_redeem))->save(array('redeem_code'=>$data['create_time'].$id));
    }
    //减少票务库存
    M('ticket')->where(array('id'=>$ticket_id))->save(array('stock'=>$re_ticket['stock']-$amount));

    $this->success('购票成功');
  }  

  public function buy1(){
    $post = $_POST;
    $ticket_id = $post['ticket_id'];
    if(!$ticket_id){
      $this->error('缺少票务号');
    }
    $amount = $post['amount'];
    if(!$amount||$amount<=0){
      $this->error('请至少购买一张票！');
    }
    if(!$post['payment']){
      $this->error('请选择支付方式！');
    }

    // 生成购票订单
    // 查询ticket信息
    $re_ticket = M('ticket')->find($ticket_id);
    //票券错误信息处理
    $current_date = time();
    if($current_date<$re_ticket['begin_date']){
      $this->error('很抱歉，您选择的票券还未开售！');
    }
    if($current_date>($re_ticket['end_date']+3600*24)){
      $this->error('很抱歉，您选择的票券已停售！');
    }
    if($re_ticket['stock']<=0){
      $this->error('很抱歉，您选择的票券已售罄！');
    }

    $post['create_time'] = time();
    $post['site'] = 2;
    $post['price'] = $re_ticket['price'];
    $post['activity_price'] = $re_ticket['price_activity'];
    
    //现金支付直接结束订单生成兑换码，打印小票，无需生成支付订单
    if($post['payment']=='3'||$post['price']===0){
      // 支付状态为已支付
      $post['status'] = 1;
      // 生成ticket_order订单
      $re_order = M('ticket_order')->add($post);
      $date = date("Ymd");
      // 更新订单号
      M('ticket_order')->where(array('id'=>$re_order))->save(array('order_num'=>$date.$re_order));
      $newcodes = array();
      for($i=0;$i<$amount;$i++){
        $data['ticket_order_id'] = $re_order;
        $data['create_time'] = time();

        $re_redeem = M('ticket_redeem_code')->add($data);
        $newcodes[] = $re_redeem;
        $len = strlen($re_redeem);
        $id = substr($re_redeem,($len-2));
        M('ticket_redeem_code')->where(array('id'=>$re_redeem))->save(array('redeem_code'=>$data['create_time'].$id));
      }
      //减少票务库存
      M('ticket')->where(array('id'=>$ticket_id))->save(array('stock'=>$re_ticket['stock']-$amount));

      $return['payment'] = $post['payment'];
      $return['price'] = $post['price'];
      $return['ticketlist'] = M('ticket_redeem_code')
      ->field('ticket_redeem_code.id,ticket_redeem_code.redeem_code,FROM_UNIXTIME(ticket_redeem_code.create_time,"%Y-%m-%d %H:%i") as create_time,exhibition.name as exhibition_name,ticket.name as ticket_name,ticket.price')
      ->join('ticket_order on ticket_order.id = ticket_redeem_code.ticket_order_id','left')
      ->join('ticket on ticket.id = ticket_order.ticket_id','left')
      ->join('exhibition on exhibition.id = ticket.exhibition_id','left')
      ->where(array('ticket_redeem_code.id'=>array('in',$newcodes)))
      ->select();
      $this->success($return);
    }else{
      //如果是微信支付（payment==‘1’）或者支付宝支付（payment==‘2’）则返回订单信息，并从前台发起支付
      // 支付状态为已下单未支付
      $post['status'] = 0;
      // 生成ticket_order订单
      $re_order = M('ticket_order')->add($post);
      $date = date("Ymd");
      // 更新订单号
      M('ticket_order')->where(array('id'=>$re_order))->save(array('order_num'=>$date.$re_order));

      $return['payment'] = $post['payment'];
      $return['price'] = $post['price'];
      $return['order_id'] = $re_order;
      $this->success($return);
    }
  }  

  // 现场支付
  public function pay(){
    $post = $_POST;
    if(!$post['pay_code']){
      $this->error('请用户出示并扫描支付码');
    }
    if(!$post['order_id']){
      $this->error('订单号为空');
    }
    //查找订单信息
    $re_order = M('ticket_order')->where(array('id'=>$post['order_id']))->find();
    if(!$re_order){
      $this->error('未查找到订单信息');
    }
    
    //微信支付
    if($post['payment']=='1'){
      //生成支付订单
      $payment['order_num'] = $re_order['id'];
      $payment['payment'] = $re_order['payment'];//1微信支付 2支付宝
      $payment['category'] = 1;
      // $payment['price'] = $re_order['price'] * $re_order['amount'];
      $payment['price'] = 0.01;
      $payment['create_time'] = time();
      $re_payment = M('payment')->add($payment);

      //更新ticket_order支付订单信息
      M('ticket_order')->where(array('id'=>$re_order['id']))->save(array('payment_num'=>$re_payment));

      if($payment['price']>0){
        // 微信支付
        //查询ticket信息
        $re_ticket = M('ticket')->find($re_order['ticket_id']);
        //查询exhibition信息
        $re_exhibition = M('exhibition')->find($re_ticket['exhibition_id']);
        $body = $re_exhibition['name'].$re_ticket['name'];
        $re=$this->wxpay($re_payment,$post['pay_code'],$body);
        if($re['status']==1){
          //支付成功
          if($re['info']['result_code']=='SUCCESS'){
            // 支付订单修改支付状态
            M('payment')->where(array('id'=>$re_payment))->save(array('status'=>1,'pay_time'=>time()));
            // 订单修改支付状态
            M('ticket_order')->where(array('id'=>$re_order['id']))->save(array('status'=>1));
            // 生成兑换码
            $newcodes = array();
            for($i=0;$i<$re_order['amount'];$i++){
              $data['ticket_order_id'] = $re_order['id'];
              $data['create_time'] = time();

              $re_redeem = M('ticket_redeem_code')->add($data);
              $newcodes[] = $re_redeem;
              $len = strlen($re_redeem);
              $id = substr($re_redeem,($len-2));
              M('ticket_redeem_code')->where(array('id'=>$re_redeem))->save(array('redeem_code'=>$data['create_time'].$id));
            }
            //减少票务库存
            M('ticket')->where(array('id'=>$ticket_id))->save(array('stock'=>$re_ticket['stock']-$re_order['amount']));
            $return['ticketlist'] = M('ticket_redeem_code')
            ->field('ticket_redeem_code.id,ticket_redeem_code.redeem_code,FROM_UNIXTIME(ticket_redeem_code.create_time,"%Y-%m-%d %H:%i") as create_time,exhibition.name as exhibition_name,ticket.name as ticket_name,ticket.price')
            ->join('ticket_order on ticket_order.id = ticket_redeem_code.ticket_order_id','left')
            ->join('ticket on ticket.id = ticket_order.ticket_id','left')
            ->join('exhibition on exhibition.id = ticket.exhibition_id','left')
            ->where(array('ticket_redeem_code.id'=>array('in',$newcodes)))
            ->select();
            $this->success($return);
          }
          // 支付失败
          if($re['info']['result_code']=='FAIL'){
            $this->error($re['info']['return_msg']);
          }
        }else{
          $this->error($re['info']);
        }
      }
    }

    //支付宝支付
    if($post['payment']=='2'){

    }

  }

  //微信支付
  public function wxpay($order_id,$auth_code,$body){
    if(!$order_id){
      $re['status'] = 0;
      $re['info'] = '缺少支付订单号';
      return($re);
    }
    if(!$auth_code||$auth_code==''){
      $re['status'] = 0;
      $re['info'] = '缺少微信支付授权码，请用户扫码';
      return($re);
    }
    $order = M('payment')->where(array('id'=>$order_id))->find();
    if(!$order){
      $re['status'] = 0;
      $re['info'] = '未查到订单';
      return($re);
    }
    if($order['status'] === '1'){
      $re['status'] = 0;
      $re['info'] = '订单已支付，请勿重复支付';
      return($re);
    }
    $tools = new JsApiPay();
    $input = new WxPayMicroPay();
    $input->SetAuth_code($auth_code);
    $input->SetBody("购票支付");
    $input->SetTotal_fee("1");
    $input->SetOut_trade_no($order_id);
    
    $microPay = new MicroPay();
    $re['info'] = $microPay->pay($input);
    $re['status'] = 1;
    return $re;

    // $re['status'] = 1;
    // $re['info'] = '订单已支付';
    // return($re);
  }

  public function wxpaycancle(){
    $microPay = new MicroPay();
    $microPay->cancel(28278);
  }

}